import React, { useEffect, useState } from 'react';
import { StyleSheet, ScrollView, Image, Dimensions, Button } from 'react-native';
import { NavigationProp, RouteProp } from '@react-navigation/native';
import { useReactive } from 'ahooks';
import HomeRequest from '../../../request/homeRequest.ts';
import to from '../../../utils/to.ts';
import { CommonStyle } from '../../../common/commonStyle.ts';
import { Loading } from '../../../component/LoadingOverlay.tsx';
import HomeHeader from './component/Header.tsx';
import HomeButtonList from './component/HomeButtonList.tsx';
import LocationClass from '../../../utils/LocationClass.ts';
import Tools from '../../../utils/Tools.ts';
import TabComponent from './component/Tab.tsx';
import { View } from 'native-base';
import HomeTemplate from './component/HomeTemplate.tsx';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState } from '../../../redux/store.ts';
import { updateBeeperID, updateBeeperParams } from '../../../redux/reducers/app.ts';

interface IHomeScreenProps {
  navigation: NavigationProp<any, 'home'>;
  route: RouteProp<{ home: any }, 'home'>;
}
interface IState {
  beeperId: number;
  bgColor: string;
  beeperList: IGetCallListRes[];
  serverList?: IServerBtnListRes;
  defaultOpen: number;
  btnModelRelations: BtnModelRelations[];
  topImgHeight: number;
}
const HomeScreen: React.FC<IHomeScreenProps> = ({ navigation, route }) => {
  const dispatch = useDispatch<AppDispatch>();
  const beeperParams = useSelector((state: RootState) => state.beeperParams);
  const state = useReactive<IState>({ beeperId: 0, bgColor: CommonStyle.mainColor, beeperList: [], serverList: undefined, defaultOpen: 1, btnModelRelations: [], topImgHeight: 150 });

  useEffect(() => {
    initializationFunction().then();
  }, []);

  // 初始化函数
  const initializationFunction = async () => {
    Loading.show();
    const [err, callList] = await to(HomeRequest.GetCallerList({ type: 2 }));
    if (err) {
      Loading.hide();
      return;
    }
    state.beeperList = callList.data;
    await fetchServerTemplate();
    Loading.hide();
  };

  // 请求服务模版
  const fetchServerTemplate = async () => {
    let serverBtnListParams: any = { query: 0 };

    const [localErr, local] = await to(LocationClass.getLocation());

    let address = undefined;
    let latitudeLongitude = undefined;
    if (local) {
      latitudeLongitude = Tools.gpsCoordinateToBaiduCoordinate(local.coords.longitude, local.coords.latitude);
      address = await Tools.getAddressFromCoordinates(latitudeLongitude.lng, latitudeLongitude.lat);
      dispatch(updateBeeperParams({ queryType: state.defaultOpen, latitude: latitudeLongitude.lat, longitude: latitudeLongitude.lng, provinceName: address.province, cityName: address.city, areaName: address.district }));
    }
    if (state.beeperId && state.beeperId > 0) {
      const selectedBeeper = state.beeperList.find((item) => item.id === state.beeperId);
      serverBtnListParams = { query: 1, type: state.defaultOpen, beeperId: state.beeperId, beeperType: selectedBeeper?.beeperType, beeperVersion: selectedBeeper?.beeperVersion };
    } else if (state.beeperId === -1) {
      //  带上经纬度
      if (local) {
        if (address && latitudeLongitude) {
          serverBtnListParams = { query: 1, latitude: latitudeLongitude.lat, longitude: latitudeLongitude.lng, provinceName: address.province, cityName: address.city, areaName: address.district };
        } else {
          serverBtnListParams = { query: 1 };
        }
      } else {
        serverBtnListParams = { query: 1 };
      }
    } else {
      if (local) {
        if (address && latitudeLongitude) {
          serverBtnListParams = { query: 0, latitude: latitudeLongitude.lat, longitude: latitudeLongitude.lng, provinceName: address.province, cityName: address.city, areaName: address.district };
        } else {
          serverBtnListParams = { query: 0 };
        }
      } else {
        serverBtnListParams = { query: 1 };
      }
    }

    const [err, serverList] = await to(HomeRequest.ServerBtnList(serverBtnListParams));
    if (err) {
      Loading.hide();
      return;
    }
    if (serverList.data) {
      state.serverList = serverList.data;
      state.beeperId = state.serverList.beeperId ? state.serverList.beeperId : -1;
      state.bgColor = state.serverList.bgColor ? state.serverList.bgColor : CommonStyle.mainColor;
      state.btnModelRelations = state.serverList.btnModelParam ? state.serverList.btnModelParam.btnModelRelations : [];
      if (state.btnModelRelations.length > 0 && state.btnModelRelations[0].moduleType === 5) {
        Image.getSize(state.btnModelRelations[0].bigImgUrl, (width, height) => {
          const windowWidth = Dimensions.get('window').width;
          const ratio = width / windowWidth;
          state.topImgHeight = height / ratio;
        });
      }
      dispatch(updateBeeperID(state.beeperId));
    }

    Loading.hide();
  };

  /**
   * 呼叫器选择点击
   * @param id
   */
  const handleHeaderBeeperClick = (id: number) => {
    Loading.show();
    state.beeperId = id;
    if (id === -1) {
      state.defaultOpen = 2;
    } else {
      state.defaultOpen = state.beeperList.find((item) => item.id === id)?.defaultOpen || 1;
    }
    fetchServerTemplate().then();
  };

  /**
   * tab精选全部选择点击
   * @param active
   */
  const handleTabChange = (active: number) => {
    Loading.show();
    state.defaultOpen = active;
    dispatch(updateBeeperParams({ ...beeperParams, queryType: active }));
    fetchServerTemplate().then();
  };

  return (
    <React.Fragment>
      <HomeHeader bgColor={state.bgColor} beeperList={state.beeperList} beeperId={state.beeperId} onRefresh={initializationFunction} onClick={handleHeaderBeeperClick} onSelected={handleHeaderBeeperClick} />
      {state.defaultOpen === 1 && state.serverList?.btnStyle === 1 && state.btnModelRelations.length > 0 && state.btnModelRelations[0].moduleType === 5 && (
        <View style={styles.topImgBox}>
          <View style={styles.halfCircle} bgColor={state.bgColor} />
          <Image style={styles.topImg} height={state.topImgHeight} resizeMode={'cover'} source={{ uri: state.btnModelRelations[0].bigImgUrl }} />
        </View>
      )}
      {state.serverList?.showLevel === 0 && <TabComponent defaultOpen={state.defaultOpen} onChange={handleTabChange} />}
      <ScrollView style={[styles.root]}>
        {(state.defaultOpen === 2 || state.serverList?.btnStyle !== 1) && <HomeButtonList serverList={state.serverList} />}
        {state.defaultOpen === 1 && state.serverList?.btnStyle === 1 && <HomeTemplate serverList={state.serverList} btnModelRelations={state.btnModelRelations} />}
        <View height={4} />
      </ScrollView>
    </React.Fragment>
  );
};
const styles = StyleSheet.create({
  root: { flex: 1, paddingHorizontal: 8, paddingVertical: 12 },
  header: { paddingHorizontal: 16 },
  topImgBox: { overflow: 'hidden', justifyContent: 'center', alignItems: 'center', paddingHorizontal: 8 },
  topImg: { width: '100%', borderRadius: 8 },
  halfCircle: { position: 'absolute', width: 500, height: 500, borderRadius: 250, top: -400, left: -73 },
});

export default HomeScreen;
